package top.xzhanyao.yowshare.dashboard.security.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.xzhanyao.yowshare.dashboard.entity.Authority;
import top.xzhanyao.yowshare.dashboard.entity.User;
import top.xzhanyao.yowshare.dashboard.service.AuthorityService;
import top.xzhanyao.yowshare.dashboard.service.UserService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthorityService authorityService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User user = userService.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException(username + " cannot be found");
        }
        // 得到用户权限的集合
        List<Authority> authorities = authorityService.selectByUsername(username);
        final Collection<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        for (Authority authority : authorities) {
            simpleGrantedAuthorities.add(new SimpleGrantedAuthority(authority.getCode()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                simpleGrantedAuthorities);
    }
}
